package com.htfyun.hardware;

import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;

public enum LedController {
    INSTANCE,
    ;

    public enum LedBreathModeAttr {
        faster(0),
        fast(1),
        slow(2),
        slower(3),
        ;
        final int mode;

        private LedBreathModeAttr(int mode) {
            this.mode = mode;
        }

        public int getMode() {
            return mode;
        }

        public static LedBreathModeAttr toMode(int mode) {
            LedBreathModeAttr m = slow;
            for (LedBreathModeAttr breathMode : LedBreathModeAttr.values()) {
                if (breathMode.getMode() == mode) {
                    m = breathMode;
                }
            }

            return m;
        }
    }

    private final static String TAG = "LedController";

    public static final int MAX_LED_NUMBER = 32;

    public static final int MAX_BRIGHTNESS = 0xff;
    public static final int MIN_BRIGHTNESS = 0x0;
    /**
     *
     * @param brightness 0~0xff
     */
    public void setAllLedBrightness(int brightness) {

        setKeyValue("leds_brightness", brightness, null, 0);

    }

    /**
     *
     * @param bits 硬件是32个灯, int 恰好是32bit. 每一个bit代表一个灯.<p></p>
     *             比如让第0个和第3个灯亮, bits = 0x9
     * @param brightness  0~0xff
     */
    public void setLedBitBrightness(int bits, int brightness) {
        setKeyValue("leds_bit", bits, "brightness", brightness);

    }

    /**
     *
     * @param mode 目前只做了四种模式
     * @param loopCount 0: 表示无限, 最大值是 0x0FFF
     */
    public void setLedBreath(LedBreathModeAttr mode, int loopCount) {

        setKeyValue("breath_mode", mode.getMode(), "loop_count", loopCount);

    }

    /**
     *
     * @param time_ms 跑马灯每移动一个灯所需时间.
     * @param loopCount 0: 表示无限
     * @param led_number 跑马灯数量, 1~31, 驱动默认是8.
     */
    public void setMarquee(int time_ms, int loopCount, int led_number) {

        led_set_marquee_led_number(led_number);
        setKeyValue("marquee_time_ms", time_ms, "loop_count", loopCount);

    }

    public int getMarqueeLedNumber() {
        return led_get_marquee_led_number();
    }

    /**
     * 设置跑马灯是顺时针还是逆时针.
     * @param anticlockwise true: 逆时针, false: 顺时针
     */
    public void setMarqueeAnticlockwise(boolean anticlockwise) {

        led_set_marquee_anticlockwise(anticlockwise);

    }

    public boolean isMarqueeAnticlockwise() {
        return led_is_marquee_anticlockwise();
    }

    /**
     * 设置待机时, 是否关闭led灯
     * @param offInSuspend
     */
    public void setOffInSuspend(boolean offInSuspend) {
        led_set_off_in_suspend(offInSuspend);
    }

    public boolean isOffInSuspend() {

        return led_is_off_in_suspend();
    }


    private void setKeyValue(String key_func, long value_func, String key_op, long value_op) {

        StringBuilder sb = new StringBuilder();
        if (TextUtils.isEmpty(key_func)) {
            return;
        }
        sb.append(key_func);
        sb.append(" = ");
        sb.append(Long.toHexString(value_func));

        if (!TextUtils.isEmpty(key_op)) {
            sb.append(" , ");

            sb.append(key_op);
            sb.append(" = ");
            sb.append(Long.toHexString(value_op));
        }


        led_control(sb.toString());
    }

    /////////////////////////////////

    private final String LED_CONTROL_PATH = "/sys/class/htfyun-leds/control";
    private final String LED_MARQUEE_LEDS_NUMBER_PATH = "/sys/class/htfyun-leds/marquee_leds_number";
    private final String LED_MARQUEE_ANTICLOCKWISE_PATH = "/sys/class/htfyun-leds/marquee_anticlockwise";
    private final String LED_OFF_IN_SUSPEND_PATH = "/sys/class/htfyun-leds/off_led_in_suspend";


    private void led_set_off_in_suspend(boolean off) {
        writeFileContent(LED_OFF_IN_SUSPEND_PATH, off ? "1" : "0");
    }

    private boolean led_is_off_in_suspend() {
        String val = readFileByLines(LED_OFF_IN_SUSPEND_PATH);
        return val.contains("1");
    }

    private void led_set_marquee_led_number(int led_number) {
        writeFileContent(LED_MARQUEE_LEDS_NUMBER_PATH, Integer.toHexString(led_number));
    }

    private int led_get_marquee_led_number() {
        String val = readFileByLines(LED_MARQUEE_LEDS_NUMBER_PATH);
        if (TextUtils.isDigitsOnly(val)) {
            return Integer.decode(val);
        }
        return -1;
    }

    private void led_set_marquee_anticlockwise(boolean anticlockwise) {
        writeFileContent(LED_MARQUEE_ANTICLOCKWISE_PATH, anticlockwise ? "1" : "0");
    }

    private boolean led_is_marquee_anticlockwise() {
        String val = readFileByLines(LED_MARQUEE_ANTICLOCKWISE_PATH);
        return val.contains("1");
    }


    private void led_control(String cmd) {
        Log.e(TAG, "cmd = " + cmd);
        writeFileContent(LED_CONTROL_PATH, cmd);
    }

    private synchronized void writeFileContent(String fileName, String content) {
        File file = new File(fileName);
        if (!file.exists()) {
            return;
        }
        Writer writer = null;
        try {
            writer = new OutputStreamWriter(new FileOutputStream(file));
            writer.write(content);
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e1) {
                }
            }
        }
    }

    public synchronized String readFileByLines(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            return "";
        }
        BufferedReader reader = null;
        StringBuilder stringBuilder = new StringBuilder("");

        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            while ((tempString = reader.readLine()) != null) {
                line++;
                stringBuilder.append(tempString.replace(" ", "").replace("\n", ""));
            }
            reader.close();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }

        return stringBuilder.toString();
    }

}
